package com.sillyhat.learningjdk.thread.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by user on 2017/3/9.
 */
public class ReentantReadWriteLockTest {
    private static ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.WriteLock wlock = rwlock.writeLock();
    private static ReentrantReadWriteLock.ReadLock rlock = rwlock.readLock();
    private static CountDownLatch cdl = new CountDownLatch(102);
    private static CyclicBarrier barriers = new CyclicBarrier(102);
    private static Map<String, String> maps = new HashMap<String, String>();

    public static void main(String[] args) throws Exception {
        long begin = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable(){
                public void run() {
                    try {
                        barriers.await();
                        rlock.lock();
                        maps.get("1");
                        TimeUnit.SECONDS.sleep(1);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        rlock.unlock();
                        cdl.countDown();
                    }
                }
            }).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        barriers.await();
                        wlock.lock();
                        maps.put("1", "2");
                        TimeUnit.SECONDS.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        wlock.unlock();
                        cdl.countDown();
                    }
                }
            }).start();
        }
        cdl.await();
        long end = System.currentTimeMillis();
        System.out.println("花费" + (end - begin) + "ms");
    }
}
